/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */
package cn.hermit.data.json.validator;

import cn.hermit.data.exception.ValidationException;

import java.util.LinkedList;
import java.util.List;

/**
 * Validator chain for JSON string validation.
 * 
 * <p>The validator chain has a default validator for basic JSON string validation.</p>
 * 
 * @author Jack Gao (Chinese name : GAO JIANGUO, Email : linux.gjg@gmail.com)
 * @date 27 Jun, 2014
 */
public class ValidatorChain implements Validator {

	private DefaultValidator validator;

	private List<Validator> validators;

	/**
	 * Constructor of ValidatorChain. Initialize default validator and 
	 * an empty list of Validator.
	 */
	public ValidatorChain() {
		validator = new DefaultValidator();
		validators = new LinkedList<Validator>();
	}

	/**
	 * Chain method for validators in chain.
	 *
	 * Validate JSON key
	 * 
	 * @param key
	 * 		JSON Key string
	 * @return
	 * 		Adjusted JSON key string
	 * @throws ValidationException
	 * 		If the validation failed, throw such exception
	 */
	@Override
	public String validateKey(String key) throws ValidationException {
		key = validator.validateKey(key);
		for (Validator validator : validators) {
			key = validator.validateKey(key);
		}
		return key;
	}

	/**
	 * 
	 * Chain method for validators in chain.
	 * 
	 * Validate JSON value
	 * 
	 * @param value
	 * 		JSON value
	 * @return
	 * 		Adjusted JSON value
	 * @throws ValidationException
	 * 		If the validation failed, throw such exception
	 */
	@Override
	public Object validateValue(Object value) throws ValidationException {
		value = validator.validateValue(value);
		for (Validator validator : validators) {
			value = validator.validateValue(value);
		}
		return value;
	}

	/**
	 * Get default validator of chain
	 * 
	 * @return
	 * 		Default validator 
	 */
	public DefaultValidator getDefaultValidator() {
		return validator;
	}

	/**
	 * Add validtor to chain.
	 * 
	 * @param validator
	 * 		JSON string validator
	 */
	public void addValidator(Validator validator) {
		this.validators.add(validator);
	}

	/**
	 * Remove validator from chain.
	 * 
	 * @param validator
	 * 		JSON string validator
	 */
	public void removeValidator(Validator validator) {
		this.validators.remove(validator);
	}

	/**
	 * Clear validators in chain
	 */
	public void clearValidators() {
		this.validators.clear();
	}

}